package com.example.wx_basketball.service.mall;

import com.example.wx_basketball.entity.mall.Order;
import com.example.wx_basketball.entity.mall.Product;
import com.example.wx_basketball.mapper.mall.OrderMapper;
import com.example.wx_basketball.mapper.mall.ProductMapper;
import org.springframework.stereotype.Service;

import org.json.JSONArray;
import org.json.JSONObject;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class OrderService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    ProductMapper productMapper;

    public void add(String orderItem, int userId) {
        String orderTime = String.valueOf(System.currentTimeMillis());
        orderMapper.add(orderItem, orderTime, userId);
    }

    public List<List<Map<String, Object>>> list(int userId) {
        List<Order> orders = orderMapper.list(userId);

        List<List<Map<String, Object>>> ordersList = new ArrayList<>();

        for (Order order : orders) {
            if (order.getOrderItem().equals("[]"))
                break;

            JSONArray arrayObj = new JSONArray(order.getOrderItem());

            List<Map<String, Object>> list = new ArrayList<>();

            // 解析每个订单中的数据
            for (int j = 0; j < arrayObj.length(); j++) {
                Map<String, Object> map = new HashMap<>();
                JSONObject jsonObject = arrayObj.getJSONObject(j);
                String productId = String.valueOf(jsonObject.get("productId"));
                String count = String.valueOf(jsonObject.get("count"));

                Product product = productMapper.getProductById(Integer.parseInt(productId));
                map.put("count", count);
                map.put("product", product);
                map.put("orderId", order.getOrderId());
                list.add(map);
            }

            ordersList.add(list);
        }

        return ordersList;
    }

}
